<template>
  <a-modal
    v-model:visible="visible"
    :title="modalTitle"
    :width="modalWidth"
    :maskClosable="false"
    :destroyOnClose="true"
    wrapClassName="custom-modal min-base-modal"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-if="modalType === 'delete'">
      <div class="text-content">是否确认删除此条数据?</div>
    </div>
    <div v-else>
      <a-form
        ref="formRef"
        inline
        :model="formData"
        :rules="rules"
        v-bind="formItemLayout"
      >
        <a-form-item label="部件名称" name="partId" required>
          <a-select
            v-model:value="formData.partId"
            allow-clear
            @change="handleSelectChange"
            placeholder="请选择部件名称"
            :options="selectList"
            :fieldNames="{
              value: 'partId',
              label: 'partName'
            }"
          />
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <a-button class="cancel" @click="handleCancel">取消</a-button>
      <a-button
        key="submit"
        type="primary"
        :loading="loading"
        @click="handleOk"
        class="common-buttom"
      >
        确认
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'

import { save, delOne } from './serve.api'

const emit = defineEmits(['isOk'])

const visible = ref<boolean>(false)
const loading = ref<boolean>(false)

const modalTitle = ref('')
const modalType = ref('')
const modalWidth = ref('')
const modalData = ref({})

const formState = ref({})

defineProps({
  selectList: {
    type: Array,
    default: () => []
  }
})

interface FormData {
  id?: undefined | string
  partId?: undefined | string
  partName: string
  deviceId: string
  deviceName: string
  isMultiplePatrol: number | string
}

const formRef = ref()
const formData = reactive<FormData>({
  id: undefined,
  partId: undefined,
  partName: '',
  deviceId: '',
  deviceName: '',
  isMultiplePatrol: ''
})

const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 24 }
}

const rules: Record<string, Rule[]> = {}

const showModal = (type: string, data?: any) => {
  visible.value = true
  modalType.value = type
  modalData.value = data

  switch (type) {
    case 'edit':
      modalTitle.value = '修改巡视点位'
      modalWidth.value = '32.25rem'
      formState.value = {}

      formData.id = data?.id
      formData.partId = data?.partId
      formData.partName = data?.partName
      formData.deviceId = data?.deviceId
      formData.deviceName = data?.deviceName
      formData.isMultiplePatrol = data?.isMultiplePatrol
      break
    case 'add':
      modalTitle.value = '新增巡视点位'
      modalWidth.value = '32.25rem'
      formState.value = {}

      formData.partId = undefined
      formData.partName = ''
      formData.deviceId = ''
      formData.deviceName = ''
      break
    case 'delete':
      modalTitle.value = '删除巡视点位'
      modalWidth.value = '26.25rem'
      break
    default:
      break
  }
}

const handleOk = async () => {
  try {
    if (modalType.value === 'delete') {
      delOneFun(modalData.value)
      return
    }

    await formRef.value.validateFields()
    if (modalType.value === 'add') {
      addFun()
    } else if (modalType.value === 'edit') {
      editFun()
    } else {
      message.error('表单填写不完整，请检查！')
    }
  } catch (error) {
    console.log('Failed:', error)
  }
}

function handleSelectChange(item: any, options: any) {
  formData.partId = options.partId
  formData.partName = options.partName
  formData.deviceId = options.deviceId
  formData.deviceName = options.deviceName
}

// 添加
const addFun = () => {
  loading.value = true
  save(
    {
      partId: formData.partId || '',
      partName: formData.partName,
      deviceId: formData.deviceId,
      deviceName: formData.deviceName
    },
    false
  )
    .then(() => {
      message.success('添加成功')
      emit('isOk')
      loading.value = false
      visible.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 编辑
const editFun = () => {
  loading.value = true
  save(formData, true)
    .then(() => {
      message.success('修改成功')
      emit('isOk')
      handleCancel()
      loading.value = false
      visible.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 删除
const delOneFun = (data: any) => {
  loading.value = true
  delOne({ id: data.id })
    .then(() => {
      loading.value = false
      visible.value = false
      message.success('删除成功')
      emit('isOk')
    })
    .catch(() => {
      loading.value = false
      visible.value = false
    })
}

// 取消
const handleCancel = () => {
  visible.value = false
  // formRef.value?.resetFields()
}

defineExpose({ showModal })
</script>
